package com.plug.controller;

import com.plug.common.consts.Code;
import com.plug.common.model.ExceptionResult;
import com.plug.common.model.JsonResult;
import com.plug.common.model.ValidateResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.validation.Valid;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * Controller控制器规范模板
 */
@Controller
@RequestMapping("/test")
public class Test {



    /**
     * ajax请求测试案例 http://localhost:8080/test/test
     * @return
     */
    @RequestMapping(value = "/test/", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<Object> test(String message){

//        if(error.hasErrors()){
//            ValidateResult validateResult = new ValidateResult(error);
//            return new ResponseEntity<Object>(validateResult, HttpStatus.BAD_REQUEST);//返回验证信息失败，暂时无配置数据验证
//        }
        JsonResult jsonResult = new JsonResult();
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", i);
            map.put("name", "name"+i+1);
            map.put("age", 18+i);
            list.add(map);
        }

        try {
            jsonResult.putData("data", list);//数据集
            jsonResult.setCode(Code.OK);//状态
            jsonResult.putData("msg", "message");//消息结果
            System.out.println(list.get(7)); //取消注释可测试异常返回结果集
            return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);//正常返回json数据
        }catch (Exception e){
            return new ResponseEntity<Object>(new ExceptionResult(e),HttpStatus.NOT_IMPLEMENTED);//返回异常数据
        }
    }

    /**
     * ajax测试修改数据请求 http://localhost:8080/test/testUpdate
     * @param name
     * @return
     */
    @RequestMapping(value = "/testUpdate",method = RequestMethod.PUT)
    @ResponseBody
    public ResponseEntity<Object> testUpdate(String name){
        JsonResult jsonResult = new JsonResult();
        jsonResult.putData("data", name);
        jsonResult.setCode(Code.OK);
        jsonResult.putData("msg", "aaaa");
        return new ResponseEntity<Object>(jsonResult,HttpStatus.OK);
    }

    /**
     * ajax测试删除数据请求 http://localhost:8080/test/testDelete
     * @param name
     * @return
     */
    @RequestMapping(value = "/testDelete/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public ResponseEntity<Object> testDelete(@RequestParam("id") int id,String name){
        JsonResult jsonResult = new JsonResult();
        jsonResult.putData("data", name);
        jsonResult.setCode(Code.OK);
        jsonResult.putData("msg", "aaaa");
        jsonResult.setCode(Code.OK);
        return new ResponseEntity<Object>(jsonResult,HttpStatus.OK);
    }

    /**
     * 转发jsp页面示例  http://localhost:8080/test/testJsp
     * @param model
     * @return
     */
    @RequestMapping(value = "/testJsp")
    public String testJsp(Model model){
        model.addAttribute("test","测试名称");//将数据带入到request对象中
        return "jsp/test";//jsp页面默认转发到WEB-INF/page/目录
    }






    /**********************************************下面为redis示例**********************************************/
    private Jedis jedis;

    public void setUp(){
        jedis = new Jedis("127.0.0.1",6379);
//        jedis.auth("root");
    }

    public static void main(String[] args) {
        String sql  = "INSERT INTO `plug_server`.`server_table` (`db`, `name`, `type`, `specific_name`, `sql_data_access`, `is_deterministic`, `definer`, `created`, `modified`, `sql_mode`, `character_set_client`, `collation_connection`, `db_collation`) " +
                "VALUES ('dd', ?, 'PROCEDURE', 'rr', 'NO_SQL', 'YES', 'qq', ?, ?, ?, 'www', 'www', 'www')";
//        String sql = "insert into `plug_local`.`task_test` (`name`,`age`,`sex`,`address`,`createtime`) values (?,?,?,?,?)";
        Connection con = null;
        PreparedStatement ps= null;
        ResultSet rs = null;
        SimpleDateFormat sdc = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/plug_local?useUnicode=true&characterEncoding=utf8", "root", "123456");
            System.out.println(con);
            ps = con.prepareStatement(sql);
            for (int i = 0; i < 300; i++) {
                System.out.println(111);
                for (int j =0; j< 20;j++){
//                    ps.setObject(1, "task" + j + 1 + ":" + sdc.format(new Date()));
//                    ps.setObject(2, new Date());
//                    ps.setObject(3, new Date());
//                    ps.setObject(4, i);
//                    ps.setObject(5, new Date());
//                    ps.setLong(2, (j + 12));
//                    ps.setString(3, "男" + j);
//                    ps.setString(4, "重庆" + j);
//                    ps.setObject(5, new Date());
                    ps.addBatch();
                }
                ps.executeBatch();
                System.out.println("第" + i + "次添加");
                Thread.sleep(50000);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("sorry can't find db driver!");
        } catch (SQLException e1) {
            e1.printStackTrace();
            System.out.println("sorry can't create Connection!");
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("thread error!");
        }finally {
            try {
                if(ps != null)
                    ps.close();
                if(con != null)
                    con.close();
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    public void setString(){
        jedis.set("test1", "21234");
        System.out.println(jedis.get("test1"));


        jedis.append("wan", "2232123wa");
        System.out.println(jedis.get("wan"));

        jedis.mset("name","liuling","age","23","qq","476777XXX");
        jedis.incr("age"); //进行加1操作
        System.out.println(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("qq"));
    }

    public void getList(){
        List<String> list = jedis.lrange("java framework",0,10);
        System.out.println(list);
    }

    public void testMap() {
         //-----添加数据----------
         Map<String, String> map = new HashMap<String, String>();
         map.put("name", "xinxin");
         map.put("age", "22");
         map.put("qq", "123456");
         jedis.hmset("user",map);
         //取出user中的name，执行结果:[minxr]-->注意结果是一个泛型的List
         //第一个参数是存入redis中map对象的key，后面跟的是放入map中的对象的key，后面的key可以跟多个，是可变参数
         List<String> rsmap = jedis.hmget("user", "name", "age", "qq");
         System.out.println(rsmap);

         //删除map中的某个键值
         jedis.hdel("user","age");
         System.out.println(jedis.hmget("user", "age")); //因为删除了，所以返回的是null
         System.out.println(jedis.hlen("user")); //返回key为user的键中存放的值的个数2
         System.out.println(jedis.exists("user"));//是否存在key为user的记录 返回true
         System.out.println(jedis.hkeys("user"));//返回map对象中的所有key
         System.out.println(jedis.hvals("user"));//返回map对象中的所有value

         Iterator<String> iter=jedis.hkeys("user").iterator();
         while (iter.hasNext()){
             String key = iter.next();
             System.out.println(key+":"+jedis.hmget("user",key));
         }
     }

    public void testList(){
         //开始前，先移除所有的内容
         jedis.del("java framework");
         System.out.println(jedis.lrange("java framework",0,-1));
         //先向key java framework中存放三条数据
         jedis.lpush("java framework","spring");
         jedis.lpush("java framework","struts");
         jedis.lpush("java framework","hibernate");
         //再取出所有数据jedis.lrange是按范围取出，
         // 第一个是key，第二个是起始位置，第三个是结束位置，jedis.llen获取长度 -1表示取得所有
         System.out.println(jedis.lrange("java framework",0,-1));

         jedis.del("java framework");
         jedis.rpush("java framework","spring");
         jedis.rpush("java framework","struts");
         jedis.rpush("java framework","hibernate");
         System.out.println(jedis.lrange("java framework",0,-1));
     }

}
